package com.lhy.utilsdemo.websocket.boot;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author Liu Hangyu
 * @date 2021/12/20 15:00
 */
@Component
@ServerEndpoint("/bootSocket")
public class BootWebsocket {


    //手动注入例子 跟下面的结果和数据例子是一套  解决service不能依赖注入的问题
//    private static InspectDetailService inspectDetailService = null;

    public static final Map<String, Session> sessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("开启");
        System.out.println(session);

    }
    @OnMessage
    public void onMessage(Session session,String message){
        System.out.println("f"+message);
        System.out.println(session.isOpen());
        while (session.isOpen()){
            System.out.println(session.isOpen());
                try {

//                    //返回结果例子
//                    Map<String, Object> result = new HashMap<String, Object>();
//                    if (inspectDetailService == null) {
//                        inspectDetailService = SpringUtil.getBean(InspectDetailService.class);
//                    }
//
//                    result.put("data",inspectDetailService.inspectionQuantityService());
//
//                    //回写数据例子
//                    session.getBasicRemote().sendText(JSONObject.toJSONString(result));


                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(1);
                    session.getBasicRemote().sendText("999");
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
    }

    @OnClose
    public void OnClose(Session session){
        System.out.println(session.isOpen());
        System.out.println("关闭");
    }

}
